package com.webcat.service.impl;

import com.alibaba.fastjson.JSON;
import com.webcat.constants.PromptTemplateConstant;
import com.webcat.dify.kb.KBResponse;
import com.webcat.dify.kb.entity.Record;
import com.webcat.entity.SseResponse;
import com.webcat.entity.vo.TopicVo;
import com.webcat.historymemory.PostgresChatMemory;
import com.webcat.service.AbstractChatService;
import com.webcat.service.QuestionService;
import com.webcat.service.ToolService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ToolServiceImpl extends AbstractChatService implements ToolService {



    @Override
    public String start() {
        return super.start();
    }

    @Override
    public Flux<SseResponse<Object>> streamChat(String chatId, String message, String toolId, Boolean multiConversation) {
        Prompt prompt;
        if (toolId != null && !toolId.isEmpty()) {
            PromptTemplate template;
            if ("1".equals(toolId)) {
                template = new PromptTemplate(PromptTemplateConstant.DB_SELECT_PROMPT_TEMPLATE);
                UserMessage userMessage = (UserMessage)template.createMessage(Map.of("question", message));
                prompt = new Prompt(userMessage);
            }
            else if ("2".equals(toolId)) {
                prompt = new Prompt(message);
            }
            else {
                prompt = new Prompt(message);
            }
        }
        else {
            prompt = new Prompt(message);
        }
        Flux<ChatResponse> chatResponseFlux = this.generateChatClient(chatId, false ,true).prompt(prompt).stream().chatResponse();
        return chatResponseFlux.map(response -> generateResponse(chatId, response));
    }

    @Override
    public String chat(String chatId, String message, String datasetId, String questionType, Boolean multiConversation) {
        return null;
    }
}
